package cn.appsys.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.service.developer.AppInfoService;
import cn.appsys.service.developer.AppVersionService;

@Controller
@RequestMapping(value = "/statics/uploadfiles/")
public class DownloadController {

	@Resource
	private AppInfoService appInfoService;

	@Resource
	private AppVersionService appVersionService;

	@RequestMapping(value = "/appId/{aid}/vid/{vid}")
	public void download(HttpServletRequest req, HttpServletResponse resp, @PathVariable String aid,
			@PathVariable String vid) {
		try {
			req.setCharacterEncoding("UTF-8");
			AppInfo appInfo = appInfoService.getAppInfo(Integer.parseInt(aid));
			if (appInfo != null) {
				AppVersion appVersion = appVersionService.getAppVersion(aid, vid);
				if (appVersion == null) {
					return;
				}
				String name = appVersion.getApkFileName();
				// 第一步：设置响应类型
				resp.setContentType("application/force-download");// 应用程序强制下载
				// 第二读取文件
				String path = "D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles/" + name;
				try (InputStream in = new FileInputStream(path)) {
					// 设置响应头，对文件进行url编码
					name = URLEncoder.encode(name, "UTF-8");
					resp.setHeader("Content-Disposition", "attachment;filename=" + name);
					resp.setContentLength(in.available());
					// 第三步：老套路，开始copy
					try (OutputStream out = resp.getOutputStream()) {
						byte[] b = new byte[1024];
						int len = 0;
						while ((len = in.read(b)) != -1) {
							out.write(b, 0, len);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
